package org.jeecg.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.bson.json.JsonObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.*;
import org.jeecg.modules.system.entity.dbanExcel.*;
import org.jeecg.modules.system.mapper.DbanInformationMapper;
import org.jeecg.modules.system.mapper.DbanRollbackRecordMapper;
import org.jeecg.modules.system.service.*;
import org.jeecg.modules.system.service.impl.SysBaseApiImpl;
import org.jeecg.modules.system.vo.SetTopVo;
import org.jeecg.modules.system.vo.TopData;
import org.jeecg.modules.system.vo.TopDataPageVo;
import org.jeecg.modules.system.vo.TopVo;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Api(tags="基础资料表")
@RestController
@RequestMapping("/dban/information")
public class DbanInformationController {
    @Autowired
    private ISysDepartService sysDepartService;
    @Autowired
    private IDbanInformationService iDbanInformationService;
    @Autowired
    private IDbanNginxFileService iDbanNginxFileService;
    @Autowired
    private IDbanAuditInfoService iDbanAuditInfoService;
    @Autowired
    private SysBaseApiImpl sysBaseApi;
    @Value("${jeecg.path.upload}")
    private String upLoadPath;
    @Autowired
    private ISysUserService iSysUserService;
    @Resource
    private DbanInformationMapper dbanInformationMapper;
    @Resource
    private DbanRollbackRecordMapper dbanRollbackRecordMapper;

    /**
     * 添加
     *
     * @param dbanInformation
     * @returnsysDepartPermission
     */
    @ApiOperation(value="基础资料表-添加", notes="基础资料表-添加")
    @PostMapping(value = "add")
    public Result<?> add(@ModelAttribute DbanInformation dbanInformation) {
        List<DbanInformation> informationList = iDbanInformationService.checkRepeat(dbanInformation);
        if (!CollectionUtils.isEmpty(informationList)) {
            return Result.ok("数据已存在，不能重复创建！");
        }
        int insertCount = iDbanInformationService.saveBaseInformatinAndFile(dbanInformation);
        if(insertCount != 0 ){
            return Result.ok("添加成功！");
        }else{
            return Result.ok("添加失败！");
        }
    }

    /**
     * 编辑信息
     */
    @RequestMapping(value = "/edit", method = {RequestMethod.POST})
    public Result<?> edit(@ModelAttribute DbanInformation dbanInformation) {
        List<DbanInformation> informationList = iDbanInformationService.checkRepeat(dbanInformation);
        if (!CollectionUtils.isEmpty(informationList)) {
            List<Integer> idList = informationList.stream().map(DbanInformation::getId).collect(Collectors.toList());
            Integer id = dbanInformation.getId();
            if (!idList.contains(id)) {
                return Result.ok("数据已存在，不能重复创建！");
            }
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = sysUser.getId();
        Integer id = dbanInformation.getId();
        DbanInformation dbanInformationDB = iDbanInformationService.getById(id);
        String createUserId = dbanInformationDB.getCreateUserId();
        if (!userId.equals(createUserId)) {
            return Result.ok("只允许操作本人数据！");
        }
        //对应撤销的动作
        int version = dbanInformationDB.getVersion();
        dbanInformation.setVersion(version + 1);
        int updateCount = iDbanInformationService.editInformation(dbanInformation);
        if (updateCount != 0) {
            return Result.ok("编辑成功！");
        } else {
            return Result.ok("编辑失败！");
        }
    }

    /**
     * 临时增加编辑location字段
     */
    @RequestMapping(value = "/edit_linshi", method = {RequestMethod.POST})
    public Result<?> editLinshi(@RequestParam("id") Integer id, @RequestParam("location") String location) {
        DbanInformation dbanInformation = new DbanInformation();
        dbanInformation.setId(id);
        dbanInformation.setLocation(location);
        //修改更新数据库
        int updateCount = dbanInformationMapper.updateById(dbanInformation);
        if (updateCount != 0) {
            return Result.ok("编辑成功！");
        } else {
            return Result.error("编辑失败！");
        }
    }

    /**
     * 分页分类列表查询
     *
     */
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(DbanInformation dbanInformation,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req) {

        QueryWrapper<DbanInformation> queryWrapper = QueryGenerator.initQueryWrapper(dbanInformation, req.getParameterMap());
        buildQueryWrapper(queryWrapper);
        queryWrapper.orderBy(true, true, "status");//状态待审核的排在前面  创建时间   更新时间
        Page<DbanInformation> page = new Page<DbanInformation>(pageNo, pageSize);
        IPage<DbanInformation> pageList = iDbanInformationService.page(page, queryWrapper);
        return Result.ok(pageList);
    }


    /**
     * 备选库列表查询
     */
    @GetMapping(value = "/beixuanku/list")
    public Result<?> queryBeiXuanKuPageList(
            DbanInformation dbanInformation,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest req) {
        dbanInformation.setStatus(DbanInfoStatusEnum.BEI_XUAN_KU.value());
        QueryWrapper<DbanInformation> queryWrapper = QueryGenerator.initQueryWrapper(dbanInformation, req.getParameterMap());
        queryWrapper.orderBy(true, false, "update_time");//状态待审核的排在前面  创建时间   更新时间
        Page<DbanInformation> page = new Page<DbanInformation>(pageNo, pageSize);
        IPage<DbanInformation> pageList = iDbanInformationService.page(page, queryWrapper);
        return Result.ok(pageList);
    }
    /**
     * 处理历史数据（增加市审核员查询）
     */
    @GetMapping("/updateUserInfo")
    public Result<?> updateUserInfo() {
        int updated = iDbanInformationService.updateUserInfo();
        return Result.ok("更新数据成功，请务必去数据做确认！");
    }

    /**
     * 资产管理列表
     * 时间范围查询在请求参数中设置
     * releaseDate_begin releaseDate_end
     */
    @GetMapping(value = "resource/list")
    public Result<?> queryResourcePageList(@RequestParam(value = "keyword", required = false) String keyword,
                                           @RequestParam(value = "type", required = false) String type,
                                           @RequestParam(value = "subject", required = false) String subject,
                                           @RequestParam(value = "fiveOneType", required = false) String fiveOneType,
                                           @RequestParam(value = "location", required = false) String location,
                                           @RequestParam(value = "goodThumb", required = false) Integer goodThumb,
                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                           HttpServletRequest req) {

        DbanInformation dbanInformation = new DbanInformation();
        if (StringUtils.isNotBlank(type)) {
            dbanInformation.setType(type);
        }
        if (StringUtils.isNotBlank(subject)) {
            dbanInformation.setSubject(subject);
        }
        if (StringUtils.isNotBlank(fiveOneType)) {
            dbanInformation.setFiveOneType(fiveOneType);
        }
        if (StringUtils.isNotBlank(location)) {
            dbanInformation.setLocation(location);
        }
        if (goodThumb != null) {
            dbanInformation.setGoodThumb(goodThumb);
        }
        dbanInformation.setStatus(DbanInfoStatusEnum.RELEASE_SUCCESS.value());
        QueryWrapper<DbanInformation> queryWrapper = QueryGenerator.initQueryWrapper(dbanInformation, req.getParameterMap());
        //对名称和关键词搜索用or连接
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.and(qr -> qr.like("name", keyword).or().like("keyword", keyword));
        }
        queryWrapper.orderByDesc("update_time");
        Page<DbanInformation> page = new Page<DbanInformation>(pageNo, pageSize);
        IPage<DbanInformation> pageList = iDbanInformationService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 获取查询条件
     */
    @GetMapping(value = "getConditions")
    public Result<?> getConditions(String type){
        Map<String, Object> conditions = iDbanInformationService.getConditions(type);
        return Result.ok(conditions);
    }

    /**
     * detail
     */
    @GetMapping(value = "/detail")
    public Result<DbanInformation> detail(@RequestParam Integer id) {
        DbanInformation dbanInformation = iDbanInformationService.getById(id);
        String type = dbanInformation.getType();
        String fiveOneType = dbanInformation.getFiveOneType();
        DbanFileNginx fileNginx = new DbanFileNginx();
        fileNginx.setInfoId(id);
        List<DbanFileNginx> fileNginxList = iDbanNginxFileService.query(fileNginx);
        if(StringUtils.isNotBlank(fiveOneType) && fiveOneType.equals("教材")) {
            Map<String, List<DbanFileNginx>> jiaoCaiMap = fileNginxList.stream().collect(Collectors.groupingBy(DbanFileNginx::getType));
            //封面图片 作者简介图片 版权页图片 目录图片 全文
            if (jiaoCaiMap.containsKey("封面图片")) {
                dbanInformation.setCoverImageList(jiaoCaiMap.get("封面图片"));
            }
            if (jiaoCaiMap.containsKey("作者简介图片")) {
                dbanInformation.setAuthorInfoImageList(jiaoCaiMap.get("作者简介图片"));
            }
            if (jiaoCaiMap.containsKey("版权页图片")) {
                dbanInformation.setCopyrightImageList(jiaoCaiMap.get("版权页图片"));
            }
            if (jiaoCaiMap.containsKey("目录图片")) {
                dbanInformation.setDirectoryImageList(jiaoCaiMap.get("目录图片"));
            }
            if (jiaoCaiMap.containsKey("全文")) {
                dbanInformation.setContentFileList(jiaoCaiMap.get("全文"));
            }
        } else if (StringUtils.isNotBlank(fiveOneType) && fiveOneType.equals("教学课程")) {
            //课程视频 课程PPT 讲稿
            Map<String, List<DbanFileNginx>> jxkcMap = fileNginxList.stream().collect(Collectors.groupingBy(DbanFileNginx::getType));
            if (jxkcMap.containsKey("课程视频")) {
                dbanInformation.setLessonVideoList(jxkcMap.get("课程视频"));
            }
            if (jxkcMap.containsKey("课程PPT")) {
                dbanInformation.setLessonpptList(jxkcMap.get("课程PPT"));
            }
            if (jxkcMap.containsKey("演讲稿")) {
                dbanInformation.setSpeechFileList(jxkcMap.get("演讲稿"));
            }
        } else if (type.equals("图书")) {
            Map<String, List<DbanFileNginx>> jiaoCaiMap = fileNginxList.stream().collect(Collectors.groupingBy(DbanFileNginx::getType));
            //封面图片 作者简介图片 版权页图片 目录图片
            if (jiaoCaiMap.containsKey("封面图片")) {
                dbanInformation.setCoverImageList(jiaoCaiMap.get("封面图片"));
            }
            if (jiaoCaiMap.containsKey("作者简介图片")) {
                dbanInformation.setAuthorInfoImageList(jiaoCaiMap.get("作者简介图片"));
            }
            if (jiaoCaiMap.containsKey("版权页图片")) {
                dbanInformation.setCopyrightImageList(jiaoCaiMap.get("版权页图片"));
            }
            if (jiaoCaiMap.containsKey("目录图片")) {
                dbanInformation.setDirectoryImageList(jiaoCaiMap.get("目录图片"));
            }
        } else {
            dbanInformation.setFileList(fileNginxList);
        }
        iDbanInformationService.addViewCount(id);
        return Result.ok(dbanInformation);
    }

    /**
     * 删除主数据
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public Result<DbanInformation> delete(@RequestParam(name = "id", required = true) Integer id) {

        Result<DbanInformation> result = new Result<DbanInformation>();
        DbanInformation dbanInformation = iDbanInformationService.getById(id);
        if (dbanInformation == null) {
            result.error500("未找到对应实体");
        } else {
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String userId = sysUser.getId();
            String createUserId = dbanInformation.getCreateUserId();
            if (!userId.equals(createUserId)) {
                return Result.ok("只允许操作本人数据！");
            }
            boolean ok = iDbanInformationService.deleteById(id);
            if (ok) {
                result.success("删除成功!");
            }
        }
        return result;
    }

    /**
     * 更改数据审核状态
     */
    @PostMapping("updateStatus")
    public Result<DbanInformation> updateStatus(@RequestParam(name = "id", required = true) Integer id,
                                                @RequestParam(name = "status", required = true) Integer status,
                                                @RequestParam(name = "remark", required = false) String remark) {
        Result<DbanInformation> result = new Result<DbanInformation>();
        DbanInformation dbanInformation = iDbanInformationService.getById(id);
        if (dbanInformation == null) {
            result.error500("未找到对应实体");
        } else {
            //第一次提交只允许自己提交自己的，然后二审提交就是自己地市的管理员可以提交二审
            //地市的数据，登录用户所属地域为地市的只能看到地市的数据，所以没问题二审提交就是自己地市的管理员可以提交二审
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String userId = sysUser.getId();
            String createUserId = dbanInformation.getCreateUserId();
            if (!userId.equals(createUserId) && status == 0) {
                return Result.ok("只允许操作本人数据！");
            }


            Integer statusDb = dbanInformation.getStatus();
            if (statusDb.intValue() == status) {
                result.success("已存在此状态，勿重复提交!");
            } else {
                Integer version = dbanInformation.getVersion();
                boolean ok = iDbanInformationService.submitInfo(id, status, remark, version);
                if (ok) {
                    result.success("提交成功!");
                }
            }

        }
        return result;
    }

    /**
     * 批量修改数据状态，前端控制状态
     * 批量审核就是针对地市管理员和省级管理员的是吧，相当于地市的批量可以吧状态改成1和4   省审核员能改成 2和3
     */
    @PostMapping("updateStatusBatch")
    public Result<?> updateStatusBatch(@RequestParam("status") Integer status, @RequestParam("ids") List<Integer> ids, @RequestParam(value = "remark", required = false) String remark) {
        for (Integer index : ids) {
            DbanInformation dbanInformation = iDbanInformationService.getById(index);
            if (dbanInformation == null) {
                return Result.ok("未找到对应实体！");
            } else {
                //第一次提交只允许自己提交自己的，然后二审提交就是自己地市的管理员可以提交二审
                //地市的数据，登录用户所属地域为地市的只能看到地市的数据，所以没问题二审提交就是自己地市的管理员可以提交二审
                LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                String userId = sysUser.getId();
                String createUserId = dbanInformation.getCreateUserId();
                if (!userId.equals(createUserId) && status == 0) {
                    return Result.ok("只允许操作本人数据！");
                }
                Integer statusDb = dbanInformation.getStatus();
                if (statusDb.intValue() == status) {
                    return Result.ok("已存在此状态，勿重复提交!");
                } else {
                    Integer version = dbanInformation.getVersion();
                    boolean ok = iDbanInformationService.submitInfo(index, status, remark, version);
                }

            }
        }
        return Result.ok("批量审核成功.");
    }

    /**
     * 提交到备选库操作
     * 市级上来的，如果状态变成了备选入库，是在市级审核员已完成里面，省级审核员备选入库里面
     */
    @PostMapping("/update/beixuan/status")
    public Result<?> updateStatusBeiXuan(@RequestParam("ids") List<Integer> ids, @RequestParam(value = "remark", required = false) String remark) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = sysUser.getUsername();
        List<String> roles = sysBaseApi.getRolesByUsername(username);
        if (roles.contains("province_asset_audit") || roles.contains("province_asset_edit")) {
            log.info("==>省人员允许操作备选库");
        } else {
            log.info("==>地级人员");
            return Result.noauth("没有权限操作入备选库.");
        }
        //更改数据状态，不记录到审核表中
        int status = 900;//900代表加入备选库状态
        int updatedStatusBatch = iDbanInformationService.updateStatusBatch(status, ids, remark);
        return Result.ok("加入备选库成功.");
    }

    /**
     * 市审核未通过4撤销->变成市审核员审核中0
     * 发布成功3撤销->变成省审核员审核中1->撤销->变成市审核员审核中0
     * 省审核未通过2撤销->省审核员审核中1->撤销->变成市审核员审核中0
     *
     * 撤销后，再次审核version恢复初始值0
     */
    @PostMapping("rollBack")
    public Result<?> rollBack(@RequestParam("id") Integer id) {
        //查看是否version = 0
        DbanInformation dbanInformation = iDbanInformationService.getById(id);
        Integer version = dbanInformation.getVersion();
        Integer cxversion = dbanInformation.getCxversion();
        if (cxversion == version.intValue()) {
            //然后我就判断数字就行了，，如果是4我就变成0    如果是3我变成1  如果是2我变成1 如果是1我就变成0
            iDbanInformationService.updateStatusById(id, 1);
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String username = sysUser.getUsername();
            String realname = sysUser.getRealname();
            DbanRobackRecord robackRecord = new DbanRobackRecord();
            robackRecord.setDataId(id);
            robackRecord.setDataName(dbanInformation.getName());
            robackRecord.setStatus(1);
            robackRecord.setUserId(realname);
            robackRecord.setUserName(username);
            dbanRollbackRecordMapper.insert(robackRecord);
            return Result.ok("撤销成功.");
        } else {
            return Result.error("数据已更新，不允许撤销.");
        }

    }


    /**
     * 根据数据id获取审核信息列表
     */
    @GetMapping("getAuditInfoList")
    public Result<?> getAuditInfoList(@RequestParam Integer id) {
        DbanAuthRecord dbanAuthRecord = new DbanAuthRecord();
        dbanAuthRecord.setPkId(id);
        List<DbanAuthRecord> dbanAuthRecords = iDbanAuditInfoService.queryInfo(dbanAuthRecord);
        return Result.ok(dbanAuthRecords);
    }

    /**
     * find_in-set函数使用
     * departIds 逗号分隔
     */
    private void buildQueryWrapper(QueryWrapper<DbanInformation> queryWrapper) {
        //角色是省级人员能能看所有的，角色是地市级只能看见自己所在区域
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = sysUser.getUsername();
        List<String> roles = sysBaseApi.getRolesByUsername(username);
        if (roles.contains("province_asset_audit") || roles.contains("province_asset_edit")) {
            log.info("==>无需进行区域过滤，省级人员能查看所有区域的数据");
        } else {
            List<String> departIdList = sysBaseApi.getDepartIdsByUsername(username);
            String departIds = String.join(",", departIdList);
            log.info("==>字符串部门:{}", departIds);
            if (!CollectionUtils.isEmpty(departIdList)) {
                if (departIdList.size() == 1) {
                    queryWrapper.like("dept_ids", departIdList.get(0));
                } else {
                    for (int i = 0; i < departIdList.size(); i++) {
                        if (i == 0) {
                            queryWrapper.apply(null != departIdList.get(i), "(find_in_set({0},dept_ids)", departIdList.get(i));
                        } else {
                            if (i == departIdList.size() - 1) {
                                queryWrapper.or().apply(null != departIdList.get(i), "find_in_set({0},dept_ids))", departIdList.get(i));
                            } else {
                                queryWrapper.or().apply(null != departIdList.get(i), "find_in_set({0},dept_ids)", departIdList.get(i));
                            }
                        }
                    }
                }
            }
        }

    }

    /**
     * 单独针对审核列表的
     * find_in-set函数使用
     * departIds 逗号分隔
     */
    private void buildQueryWrapper(QueryWrapper<DbanInformation> queryWrapper, Integer status) {
        //角色是省级人员能能看所有的，角色是地市级只能看见自己所在区域
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = sysUser.getUsername();
        List<String> roles = sysBaseApi.getRolesByUsername(username);
        if (roles.contains("province_asset_audit") || roles.contains("province_asset_edit")) {
            if (status == 0) {
                //省级待审核
                queryWrapper.eq("status", 1);
            } else if (status == 1) {
                //省级已审核
                queryWrapper.eq("status", 3);
            } else if (status == 2) {
                queryWrapper.and(qr -> qr.eq("status", 2).or().eq("status", 4));

                //省级已退回 所有省级审核员操作的
//                queryWrapper.eq("status", 2).or().eq("status", 4);
                //查询所有省级人员审核的Pkid
                List<SysUser> shengJiAuditUserInfo = iSysUserService.getShengJiAuditUserInfo();
                List<String> userIds = new ArrayList<>();
                for (SysUser index : shengJiAuditUserInfo) {
                    userIds.add(index.getId());
                }
                List<DbanAuthRecord> dbanAuthRecords = iDbanAuditInfoService.queryByUserIds(userIds);
                if (!CollectionUtils.isEmpty(dbanAuthRecords)) {
                    Set<Integer> pkIdSet = new HashSet<>();
                    for (DbanAuthRecord index : dbanAuthRecords) {
                        pkIdSet.add(index.getPkId());
                    }
                    List<Integer> pkIdList = new ArrayList<>(pkIdSet);
                    queryWrapper.in("id", pkIdList);
                }
            } else {
                throw new RuntimeException("==>没有此参数:{}" + status);
            }
        } else {
            List<String> departIdList = sysBaseApi.getDepartIdsByUsername(username);
            String departIds = String.join(",", departIdList);
            log.info("==>字符串部门:{}", departIds);
            if (!CollectionUtils.isEmpty(departIdList)) {
                if (departIdList.size() == 1) {
                    queryWrapper.like("dept_ids", departIdList.get(0));
                } else {
                    for (int i = 0; i < departIdList.size(); i++) {
                        if (i == 0) {
                            queryWrapper.apply(null != departIdList.get(i), "(find_in_set({0},dept_ids)", departIdList.get(i));
                        } else {
                            if (i == departIdList.size() - 1) {
                                queryWrapper.or().apply(null != departIdList.get(i), "find_in_set({0},dept_ids))", departIdList.get(i));
                            } else {
                                queryWrapper.or().apply(null != departIdList.get(i), "find_in_set({0},dept_ids)", departIdList.get(i));
                            }
                        }
                    }
                }
            }
            if (status == 0) {
                //市级待审核
                queryWrapper.eq("status", 0).or().eq("status", 2);
            } else if (status == 1) {
                //市级已审核
                queryWrapper.eq("status", 1).or().eq("status", 3);
            } else if (status == 2) {
                //市级已退回
                queryWrapper.eq("status", 4);
            } else {
                throw new RuntimeException("==>没有次参数:{}" + status);
            }
        }

    }



    /**
     * 资源库导出
     */
    @RequestMapping(value = "resource/exportXls")
    public ModelAndView resourceExportXls(@RequestParam(value = "keyword", required = false) String keyword,
                                           @RequestParam(value = "type", required = false) String type,
                                           @RequestParam(value = "subject", required = false) String subject,
                                           @RequestParam(value = "fiveOneType", required = false) String fiveOneType,
                                          @RequestParam(value = "location", required = false) String location,
                                           HttpServletRequest req) {

        DbanInformation dbanInformation = new DbanInformation();
        if (StringUtils.isNotBlank(type)) {
            dbanInformation.setType(type);
        }
        if (StringUtils.isNotBlank(subject)) {
            dbanInformation.setSubject(subject);
        }
        if (StringUtils.isNotBlank(fiveOneType)) {
            dbanInformation.setFiveOneType(fiveOneType);
        }
        if (StringUtils.isNotBlank(location)) {
            dbanInformation.setLocation(location);
        }
        dbanInformation.setStatus(DbanInfoStatusEnum.RELEASE_SUCCESS.value());
        QueryWrapper<DbanInformation> queryWrapper = QueryGenerator.initQueryWrapper(dbanInformation, req.getParameterMap());
        //对名称和关键词搜索用or连接
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.and(qr -> qr.like("name", keyword).or().like("keyword", keyword));
        }
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //update-begin--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据--------------------
//        String selections = req.getParameter("selections");
//        if (!oConvertUtils.isEmpty(selections)) {
//            queryWrapper.in("id", selections.split(","));
//        }
        //update-end--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据----------------------
        List<DbanInformation> pageList = iDbanInformationService.list(queryWrapper);
        List<AuditBaseResourceModel> modelList = new ArrayList<>();
        for (DbanInformation index : pageList) {
            AuditBaseResourceModel model = new AuditBaseResourceModel();
            BeanUtils.copyProperties(index, model);
            String typeModel = model.getType();
            if (typeModel.equals("五个一批好成果")) {
                model.setType(index.getFiveOneType());
            }
            modelList.add(model);
        }
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "资源库列表信息");
        mv.addObject(NormalExcelConstants.CLASS, AuditBaseResourceModel.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ExportParams exportParams = new ExportParams("资源库列表信息数据", "导出人:" + user.getRealname(), "导出信息");
        exportParams.setImageBasePath(upLoadPath);
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, modelList);
        return mv;
    }


    /**
     * 导出基础资料和五个一批好成果excel
     *
     * @param request
     */
    @RequestMapping(value = "exportXls")
    public ModelAndView exportXls(DbanInformation dbanInformation, HttpServletRequest request) {
        // Step.1 组装查询条件
        QueryWrapper<DbanInformation> queryWrapper = QueryGenerator.initQueryWrapper(dbanInformation, request.getParameterMap());
        buildQueryWrapper(queryWrapper);        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //update-begin--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据--------------------
        String selections = request.getParameter("selections");
        if (!oConvertUtils.isEmpty(selections)) {
            queryWrapper.in("id", selections.split(","));
        }
        //update-end--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据----------------------
        List<DbanInformation> pageList = iDbanInformationService.list(queryWrapper);
        String type = dbanInformation.getType();
        if (type.equals("图片")) {
            List<ImageModel> imageModelList = new ArrayList<>();
            for (DbanInformation index : pageList) {
                ImageModel imageModel = new ImageModel();
                BeanUtils.copyProperties(index, imageModel);
                imageModelList.add(imageModel);
            }
            //导出文件名称
            mv.addObject(NormalExcelConstants.FILE_NAME, "图片资源信息");
            mv.addObject(NormalExcelConstants.CLASS, ImageModel.class);
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            ExportParams exportParams = new ExportParams("图片资源信息列表数据", "导出人:" + user.getRealname(), "导出信息");
            exportParams.setImageBasePath(upLoadPath);
            mv.addObject(NormalExcelConstants.PARAMS, exportParams);
            mv.addObject(NormalExcelConstants.DATA_LIST, imageModelList);
        } else if (type.equals("视频")) {
            List<VideoModel> modelList = new ArrayList<>();
            for (DbanInformation index : pageList) {
                VideoModel model = new VideoModel();
                BeanUtils.copyProperties(index, model);
                modelList.add(model);
            }
            //导出文件名称
            mv.addObject(NormalExcelConstants.FILE_NAME, "视频资源信息");
            mv.addObject(NormalExcelConstants.CLASS, VideoModel.class);
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            ExportParams exportParams = new ExportParams("视频资源信息列表数据", "导出人:" + user.getRealname(), "导出信息");
            exportParams.setImageBasePath(upLoadPath);
            mv.addObject(NormalExcelConstants.PARAMS, exportParams);
            mv.addObject(NormalExcelConstants.DATA_LIST, modelList);
        } else if (type.equals("音频")) {
            List<RadioModel> modelList = new ArrayList<>();
            for (DbanInformation index : pageList) {
                RadioModel model = new RadioModel();
                BeanUtils.copyProperties(index, model);
                modelList.add(model);
            }
            //导出文件名称
            mv.addObject(NormalExcelConstants.FILE_NAME, "音频资源信息");
            mv.addObject(NormalExcelConstants.CLASS, RadioModel.class);
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            ExportParams exportParams = new ExportParams("音频资源信息列表数据", "导出人:" + user.getRealname(), "导出信息");
            exportParams.setImageBasePath(upLoadPath);
            mv.addObject(NormalExcelConstants.PARAMS, exportParams);
            mv.addObject(NormalExcelConstants.DATA_LIST, modelList);
        } else if (type.equals("图书")) {
            List<BookModel> modelList = new ArrayList<>();
            for (DbanInformation index : pageList) {
                BookModel model = new BookModel();
                BeanUtils.copyProperties(index, model);
                modelList.add(model);
            }
            //导出文件名称
            mv.addObject(NormalExcelConstants.FILE_NAME, "图书资源信息");
            mv.addObject(NormalExcelConstants.CLASS, BookModel.class);
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            ExportParams exportParams = new ExportParams("图书资源信息列表数据", "导出人:" + user.getRealname(), "导出信息");
            exportParams.setImageBasePath(upLoadPath);
            mv.addObject(NormalExcelConstants.PARAMS, exportParams);
            mv.addObject(NormalExcelConstants.DATA_LIST, modelList);
        } else if (type.equals("文章")) {
            List<ArticleModel> modelList = new ArrayList<>();
            for (DbanInformation index : pageList) {
                ArticleModel model = new ArticleModel();
                BeanUtils.copyProperties(index, model);
                modelList.add(model);
            }
            //导出文件名称
            mv.addObject(NormalExcelConstants.FILE_NAME, "文章资源信息");
            mv.addObject(NormalExcelConstants.CLASS, ArticleModel.class);
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            ExportParams exportParams = new ExportParams("文章资源信息列表数据", "导出人:" + user.getRealname(), "导出信息");
            exportParams.setImageBasePath(upLoadPath);
            mv.addObject(NormalExcelConstants.PARAMS, exportParams);
            mv.addObject(NormalExcelConstants.DATA_LIST, modelList);
        } else if (type.equals("文件")) {
            List<FileModel> modelList = new ArrayList<>();
            for (DbanInformation index : pageList) {
                FileModel model = new FileModel();
                BeanUtils.copyProperties(index, model);
                modelList.add(model);
            }
            //导出文件名称
            mv.addObject(NormalExcelConstants.FILE_NAME, "文件资源信息");
            mv.addObject(NormalExcelConstants.CLASS, FileModel.class);
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            ExportParams exportParams = new ExportParams("文件资源信息列表数据", "导出人:" + user.getRealname(), "导出信息");
            exportParams.setImageBasePath(upLoadPath);
            mv.addObject(NormalExcelConstants.PARAMS, exportParams);
            mv.addObject(NormalExcelConstants.DATA_LIST, modelList);
        } else if (type.equals("五个一批好成果")) {
            String fiveOneType = dbanInformation.getFiveOneType();
            if (fiveOneType.equals("理论文章")) {
                List<WgyphcgArticle> modelList = new ArrayList<>();
                for (DbanInformation index : pageList) {
                    WgyphcgArticle model = new WgyphcgArticle();
                    BeanUtils.copyProperties(index, model);
                    modelList.add(model);
                }
                //导出文件名称
                mv.addObject(NormalExcelConstants.FILE_NAME, "理论文章资源信息");
                mv.addObject(NormalExcelConstants.CLASS, WgyphcgArticle.class);
                LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                ExportParams exportParams = new ExportParams("理论文章资源信息列表数据", "导出人:" + user.getRealname(), "导出信息");
                exportParams.setImageBasePath(upLoadPath);
                mv.addObject(NormalExcelConstants.PARAMS, exportParams);
                mv.addObject(NormalExcelConstants.DATA_LIST, modelList);

            } else if (fiveOneType.equals("咨询报告")) {
                List<WgyphcgReport> modelList = new ArrayList<>();
                for (DbanInformation index : pageList) {
                    WgyphcgReport model = new WgyphcgReport();
                    BeanUtils.copyProperties(index, model);
                    modelList.add(model);
                }
                //导出文件名称
                mv.addObject(NormalExcelConstants.FILE_NAME, "咨询报告资源信息");
                mv.addObject(NormalExcelConstants.CLASS, WgyphcgReport.class);
                LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                ExportParams exportParams = new ExportParams("咨询报告资源信息列表数据", "导出人:" + user.getRealname(), "导出信息");
                exportParams.setImageBasePath(upLoadPath);
                mv.addObject(NormalExcelConstants.PARAMS, exportParams);
                mv.addObject(NormalExcelConstants.DATA_LIST, modelList);
            } else if (fiveOneType.equals("教材")) {
                List<WgyphcgBook> modelList = new ArrayList<>();
                for (DbanInformation index : pageList) {
                    WgyphcgBook model = new WgyphcgBook();
                    BeanUtils.copyProperties(index, model);
                    modelList.add(model);
                }
                //导出文件名称
                mv.addObject(NormalExcelConstants.FILE_NAME, "教材资源信息");
                mv.addObject(NormalExcelConstants.CLASS, WgyphcgBook.class);
                LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                ExportParams exportParams = new ExportParams("教材资源信息列表数据", "导出人:" + user.getRealname(), "导出信息");
                exportParams.setImageBasePath(upLoadPath);
                mv.addObject(NormalExcelConstants.PARAMS, exportParams);
                mv.addObject(NormalExcelConstants.DATA_LIST, modelList);
            } else if (fiveOneType.equals("教学课程")) {
                List<WgyphcgLesson> modelList = new ArrayList<>();
                for (DbanInformation index : pageList) {
                    WgyphcgLesson model = new WgyphcgLesson();
                    BeanUtils.copyProperties(index, model);
                    modelList.add(model);
                }
                //导出文件名称
                mv.addObject(NormalExcelConstants.FILE_NAME, "教学课程资源信息");
                mv.addObject(NormalExcelConstants.CLASS, WgyphcgLesson.class);
                LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                ExportParams exportParams = new ExportParams("教学课程资源信息列表数据", "导出人:" + user.getRealname(), "导出信息");
                exportParams.setImageBasePath(upLoadPath);
                mv.addObject(NormalExcelConstants.PARAMS, exportParams);
                mv.addObject(NormalExcelConstants.DATA_LIST, modelList);
            } else {
                log.warn("==>没有这个类型,fiveOneType:{}", fiveOneType);
            }
        } else {
            log.warn("==>没有此类型.");
        }
        return mv;
    }

    /**
     * 校长删除信息，这个接口只提供给校长角色的人员使用
     * president
     */
    @RequestMapping(value = "/super/delete", method = RequestMethod.POST)
    public Result<?> superDelete(@RequestParam(name = "id", required = true) Integer id) {
        Result<DbanInformation> result = new Result<DbanInformation>();
        //判断是校长角色
        String tipMssg = iDbanInformationService.deleteByPresident(id);
        result.success(tipMssg);
        return result;
    }

    /**
     * 五个一批好成果-分页审核列表信息
     */
    @GetMapping(value = "auditInfo/list")
    public Result<?> queryAuditInfoPageList(DbanInformation dbanInformation,
                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                            HttpServletRequest req) {

        IPage<DbanInformation> pageList = iDbanAuditInfoService.pageListAuditInfo(dbanInformation, pageNo, pageSize, req);
        return Result.ok(pageList);

//        Integer status = dbanInformation.getStatus();
//        QueryWrapper<DbanInformation> queryWrapper = QueryGenerator.initQueryWrapper(dbanInformation, req.getParameterMap());
//        if (status == null) {
//            queryWrapper.ne("status", -1);
//        }
//        buildQueryWrapper(queryWrapper, status);
//        Page<DbanInformation> page = new Page<DbanInformation>(pageNo, pageSize);
//        IPage<DbanInformation> pageList = iDbanInformationService.page(page, queryWrapper);
//        //挂接地市、市审核员、流转状态、审核时间
//        List<DbanInformation> records = pageList.getRecords();
//        if (!CollectionUtils.isEmpty(records)) {
//            List<Integer> idList = records.stream().map(DbanInformation::getId).collect(Collectors.toList());
//            List<DbanAuthRecord> dbanAuthRecords = iDbanAuditInfoService.queryByPkIds(idList);
//            //按照时间排序，取list集合中的第一个
//            Map<Integer, List<DbanAuthRecord>> map = dbanAuthRecords.stream().collect(Collectors.groupingBy(DbanAuthRecord::getPkId));
//            SimpleDateFormat sb = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            for (DbanInformation index : records) {
//                String deptIds = index.getDeptIds();//暂时考虑一个用户属于一个地市的情况
//                SysDepart sysDepartEntity = sysDepartService.getById(deptIds);
//                String departName = sysDepartEntity.getDepartName();
//                index.setCityName(departName);
//                Integer id = index.getId();
//                List<DbanAuthRecord> authRecordList = map.get(id);
//                DbanAuthRecord record = authRecordList.get(0);//按照时间排序，取list集合中的第一个
//                index.setCityAuditUserName(record.getRealName());
//                index.setAuditStatus(record.getStatusTxt());
//                index.setAuditDate(sb.format(record.getCreateTime()));
//            }
//        }
//        return Result.ok(pageList);

    }

    /**
     * 基础资料类（文章、图片、图书、视频、音频）-分页审核列表信息
     */
    @GetMapping(value = "auditBaseInfo/list")
    public Result<?> queryauditBaseInfoPageList(DbanInformation dbanInformation,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                HttpServletRequest req) {

        IPage<DbanInformation> pageList = iDbanAuditInfoService.pageListAuditInfo(dbanInformation, pageNo, pageSize, req);
        return Result.ok(pageList);

//        Integer status = dbanInformation.getStatus();
//        QueryWrapper<DbanInformation> queryWrapper = QueryGenerator.initQueryWrapper(dbanInformation, req.getParameterMap());
//        //排查五个一批好成果数据
//        queryWrapper.ne("type", "五个一批好成果");
//        if (status == null) {
//            queryWrapper.ne("status", -1);
//        }
//        buildQueryWrapper(queryWrapper, status);
//        Page<DbanInformation> page = new Page<DbanInformation>(pageNo, pageSize);
//        IPage<DbanInformation> pageList = iDbanInformationService.page(page, queryWrapper);
//        //挂接地市、市审核员、流转状态、审核时间
//        List<DbanInformation> records = pageList.getRecords();
//        if (!CollectionUtils.isEmpty(records)) {
//            List<Integer> idList = records.stream().map(DbanInformation::getId).collect(Collectors.toList());
//            List<DbanAuthRecord> dbanAuthRecords = iDbanAuditInfoService.queryByPkIds(idList);
//            //按照时间排序，取list集合中的第一个
//            Map<Integer, List<DbanAuthRecord>> map = dbanAuthRecords.stream().collect(Collectors.groupingBy(DbanAuthRecord::getPkId));
//            SimpleDateFormat sb = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            for (DbanInformation index : records) {
//                String deptIds = index.getDeptIds();//暂时考虑一个用户属于一个地市的情况
//                SysDepart sysDepartEntity = sysDepartService.getById(deptIds);
//                String departName = sysDepartEntity.getDepartName();
//                index.setCityName(departName);
//                Integer id = index.getId();
//                List<DbanAuthRecord> authRecordList = map.get(id);
//                DbanAuthRecord record = authRecordList.get(0);//按照时间排序，取list集合中的第一个
//                index.setCityAuditUserName(record.getRealName());
//                index.setAuditStatus(record.getStatusTxt());
//                index.setAuditDate(sb.format(record.getCreateTime()));
//            }
//        }
//        return Result.ok(pageList);
    }
    //=================================================================================================================

    /**
     * 给数据点“好”
     */
    /**
     * 临时增加编辑location字段
     */
    @RequestMapping(value = "/editgood", method = {RequestMethod.POST})
    public Result<?> editgood(@RequestParam("id") Integer id) {
        Result<DbanInformation> result = new Result<DbanInformation>();
        DbanInformation dbanInformationDB = iDbanInformationService.getById(id);
        if (dbanInformationDB == null) {
            result.error500("未找到对应实体");
            return result;
        } else {
            Integer goodThumb = dbanInformationDB.getGoodThumb();
            DbanInformation dbanInformation = new DbanInformation();
            dbanInformation.setId(id);
            //之前是0变为1，之前是1变为0
            dbanInformation.setGoodThumb(goodThumb == DbanInfoGoodThumbEnum.INIT.value() ? DbanInfoGoodThumbEnum.GOOD.value() : DbanInfoGoodThumbEnum.INIT.value());
            //修改更新数据库
            int updateCount = dbanInformationMapper.updateById(dbanInformation);
            if (updateCount != 0) {
                return Result.ok("操作成功！");
            } else {
                return Result.error("操作失败！");
            }
        }
    }

    //=========================================================================================================
    /**
     * 查询置顶数据列表
     * */
    @GetMapping(value = "/queryDbanInformationListByTop")
    public Result<?> queryDbanInformationListByTop(@RequestParam(value = "isTop",required = false) Integer isTop){
        List<DbanInformation> mList = iDbanInformationService.queryDbanInformationByTop(isTop);
        return Result.ok(mList);
    }

    /**
     * 设置一条数据为置顶或取消置顶
     * */
    @PostMapping(value = "/updateDbanInfoSetTop")
    public Result<?> updateDbanInfoSetTop(@RequestBody SetTopVo setTopVo){

        int updateIsTop = iDbanInformationService.updateDbanInformationTop(setTopVo.getId(),setTopVo.getTopId(),setTopVo.getIsTop());
        if (updateIsTop != 0) {
            return Result.ok("操作成功！");
        } else {
            return Result.error("操作失败！");
        }
    }

    /**
     * 批量设置置顶或取消置顶
     * 是否置顶，0：是，1：否
     * {
     *      [
     *         {
     *             "id": 1,
     *             "topId: 1,
     *             "isTop": 0
     *         },
     *        {
     *             "id": 2,
     *             "topId: 1,
     *             "isTop": 0
     *         }
     *      ]
     * }
     * */
    @PostMapping(value = "/updateDbanInfoBatchTop")
    public Result<?> updateDbanInfoBatchTop(@RequestBody TopVo topVo){

        List<TopData> topData = topVo.getTopData();
        for(int i=0; i<topData.size(); i++){
            int id = topData.get(i).getId();
            int topId = topData.get(i).getTopId();
            int isTop = topData.get(i).getIsTop();
            iDbanInformationService.updateDbanInformationTop(id,topId,isTop);
        }
        return Result.ok("操作成功！");
    }

    /**
     * 查询基础资源管理列表是否置顶
     * */
    @PostMapping(value = "/queryBaseDbanInformationByTop")
    public Result<?> queryBaseDbanInformationByTop(@RequestBody TopDataPageVo topDataPageVo){

        int pageNo = topDataPageVo.getPageNo();
        int pageSize = topDataPageVo.getPageSize();
        String type = topDataPageVo.getType();
        int isTop = topDataPageVo.getIsTop();

        IPage<DbanInformation> mList = iDbanInformationService.queryBaseDbanInformationByTop(pageNo,pageSize,type,isTop);
        return Result.ok(mList);
    }

    /**
     * 查询五个好一批成果列表是否置顶
     * */
    @PostMapping(value = "/queryFiveOneDbanInformationByTop")
    public Result<?> queryFiveOneDbanInformationByTop(@RequestBody TopDataPageVo topDataPageVo){

        int pageNo = topDataPageVo.getPageNo();
        int pageSize = topDataPageVo.getPageSize();
        String fiveOneType = topDataPageVo.getFiveOneType();
        int isTop = topDataPageVo.getIsTop();

        IPage<DbanInformation> mList = iDbanInformationService.queryFiveOndDbanInformationByTop(pageNo,pageSize,fiveOneType,isTop);
        return Result.ok(mList);
    }

    /**
     * 查询单个资源列表
     * */
    @GetMapping(value = "/queryUnitDbanInformationByTopList")
    public Result<?> queryUnitDbanInformationByTopList(@RequestParam(value = "type",required = false) String type,
                                                       @RequestParam(value = "isTop",required = false) Integer isTop){
        List<DbanInformation> mList = iDbanInformationService.queryBaseDbanInformationByTopList(type,isTop);
        return Result.ok(mList);
    }


    //=========================================================================================================
}
